angular.module('Controllers',[])
	.controller('loginCtrl', function ($scope, $location, $rootScope, $socket){		// Login Controller
		// Varialbles Initialization.
		$scope.userAvatar = "Avatar1.jpg";
		$scope.isErrorReq = false;
		$scope.isErrorNick = false;
		$scope.username = "";

		// redirection if user logged in.
		if($rootScope.loggedIn){
			$location.path('/v1/ChatRoom');
		}

	// Functions for controlling behaviour.
	$scope.redirect = function(){
		console.log("username:"+$scope.username);
		console.log("password:"+$scope.password);
		var isValid = $scope.loginCheck();
		if(!isValid)
		{
			return;
		}
		$socket.emit('new user',{username : $scope.username,password : $scope.password, userAvatar : $scope.userAvatar},function(data){
			if(data.success == true){	
				// login success
				$rootScope.username = $scope.username;
				$rootScope.userAvatar = $scope.userAvatar;
				$rootScope.loggedIn = true;
				$location.path('/v1/ChatRoom');
			}else{
				// login failed
				$scope.printErr(data.msg);
			}
		});
	}

	$scope.loginCheck = function(){
		var isValid = true ;
		if(!$scope.username){
			// blanck nickname 
			$scope.errMsg = "Enter a username.";
			$scope.isErrorNick = true;
			//$scope.isErrorReq = true;
			$scope.printErr($scope.errMsg);
			isValid = false ;
		}
		if(!$scope.password){
			// blanck nickname 
			$scope.errMsg = "Enter a password.";
			$scope.isErrorPwd = true;
			//$scope.isErrorReq = true;
			$scope.printErr($scope.errMsg);
			isValid = false ;
		}
		if ($scope.username.length > 20) {
			// nickname greater than limit
			$scope.errMsg = "username exceed 20 charachters.";
			$scope.isErrorNick = true;
			//$scope.isErrorReq = true;
			$scope.printErr($scope.errMsg);
			isValid = false ;
		}
		if ($scope.password.length > 20) {
			// nickname greater than limit
			$scope.errMsg = "password exceed 20 charachters.";
			$scope.isErrorPwd = true;
			//$scope.isErrorReq = true;
			$scope.printErr($scope.errMsg);
			isValid = false ;
		}
		return isValid ;
	}
	$scope.printErr = function(msg){	// popup for error message
		//显示错误信息 , 显示1秒
		var html = '<p id="alert">'+ msg +'</p>';
		if ($( ".chat-box" ).has( "p" ).length < 1) {
			$(html).hide().prependTo(".chat-box").fadeIn(1500);
			$('#alert').delay(1000).fadeOut('slow', function(){
				$('#alert').remove();
			});
		};
	}
	$scope.changeAvatar = function(avatar){		// secting different avatar
			$scope.userAvatar = avatar;
	}
})
